<template>
  <div 
    class="column-component"
    :class="{ 
      'editable': isEditable,
      'has-children': localChildren.length > 0,
      'is-selected': isSelected,
      'is-container': true
    }"
    :style="{ 
      padding: '1rem',
      backgroundColor: 'transparent',
      minHeight: '60px',
      border: '1px solid #e2e8f0'
    }"
    @click.stop="$emit('click', $event)"
  >
    <!-- 列标题和操作区 -->
    <div v-if="isEditable" class="column-header flex justify-between items-center mb-2">
      <div class="flex items-center text-sm">
        <i class="fa fa-columns text-primary mr-2"></i>
        <span>行组件</span>
        <span v-if="localChildren.length" class="ml-2 text-gray-500">({{ localChildren.length }}个子元素)</span>
      </div>
      <!-- 添加子组件按钮 -->
      <button 
        class="p-1 bg-primary text-white hover:bg-primary/90 rounded shadow-sm"
        @click.stop="requestAddChild"
        title="添加子组件"
      >
        <i class="fa fa-plus text-xs"></i>
      </button>
    </div>
    
    <!-- 列内容区域 -->
    <div 
      class="column-content"
    >
      <!-- 子元素列表 -->
      <div class="w-full">
        <template v-for="(child, index) in localChildren" :key="getChildKey(child, index)">
          <!-- 渲染子组件 -->
          <div class="child-wrapper relative" :data-child-index="index">
            <!-- 子组件操作按钮 -->
            <div v-if="isEditable" class="child-actions absolute top-0 right-0 z-50 flex gap-1 opacity-100 transition-opacity">
              <button 
                v-if="index > 0" 
                class="p-1 bg-white text-gray-400 hover:text-primary hover:bg-primary/10 rounded shadow-sm"
                @click.stop="moveChildUp(index)"
                title="上移"
              >
                <i class="fa fa-arrow-up text-xs"></i>
              </button>
              <button 
                v-if="index < localChildren.length - 1" 
                class="p-1 bg-white text-gray-400 hover:text-primary hover:bg-primary/10 rounded shadow-sm"
                @click.stop="moveChildDown(index)"
                title="下移"
              >
                <i class="fa fa-arrow-down text-xs"></i>
              </button>
              <button 
                class="p-1 bg-white text-gray-400 hover:text-primary hover:bg-primary/10 rounded shadow-sm"
                @click.stop="requestChildSettings(index)"
                title="设置"
              >
                <i class="fa fa-cog text-xs"></i>
              </button>
              <button 
                class="p-1 bg-white text-gray-400 hover:text-red-500 hover:bg-red-50 rounded shadow-sm"
                @click.stop="deleteChild(index)"
                title="删除"
              >
                <i class="fa fa-times text-xs"></i>
              </button>
            </div>
            
            <component
              :is="child.config.component"
              v-bind="child.props"
              :children="child.children || []"
              v-on="getChildEventListeners(child, index)"
              class="child-component"
              :is-selected="child.isSelected"
              :is-editable="isEditable"
              @child-event="handleNestedChildEvent(index, $event)"
            ></component>
          </div>
        </template>
        
        <!-- 空状态提示 -->
        <div v-if="localChildren.length === 0" class="empty-state text-center py-6 text-gray-400 text-sm">
          <i class="fa fa-plus-circle mr-1"></i> 组件内容区域
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, nextTick, onMounted, reactive } from 'vue';

export default {
  // 低代码平台元数据 - 标记为容器组件
   lowcode: {
    meta: {
      name: 'row',
      icon: 'fa-th-large',
      displayName: '行组件',
      description: '',
      category: '容器组件',
      isContainer: true  // 标记为容器组件
    },
    configPanel:[],
    events: [],
    actions: [],
  },
  props: {
    props: {
      type: Object,
      default: () => ({})
    },
    children: {
      type: Array,
      default: () => []
    },
    isSelected: {
      type: Boolean,
      default: false
    },
    isEditable: {
      type: Boolean,
      default: true
    }
  },
  emits: [
    // 操作事件
    'delete',
    'request-settings',
    'click',
    // 子组件事件
    'child-event'
  ],
  setup(props, { emit }) {
    const dropPosition = ref(-1);
    const isDraggingOver = ref(false);
    
    // 创建本地响应式数组来管理子组件数据
    const localChildren = reactive([...props.children]);
    
    // 监听props.children的变化，同步到本地数组
    watch(() => props.children, (newChildren) => {
      localChildren.splice(0, localChildren.length, ...newChildren);
    }, { deep: true });

    // 简化处理，移除拖拽相关功能
    // 如有需要添加子组件，可以通过其他方式实现
    // 这里保留原有的事件处理函数，但移除了拖拽逻辑

    // 处理嵌套子组件的事件
    const handleNestedChildEvent = (parentIndex, event) => {
      console.log('处理嵌套子组件事件:', event.type, parentIndex);
      
      // 对于设置请求，需要将事件继续向上传递
      if (event.type === 'request-child-settings') {
        emit('child-event', {
          type: 'request-child-settings',
          data: {
            ...event.data,
            // 更新路径信息，添加当前组件的索引
            path: [props.props.id, ...event.data.path]
          }
        });
      } else if (event.type === 'local-move-child' || event.type === 'local-delete-child') {
        // 对于其他类型的事件，保留原有处理逻辑
        emit('child-event', event);
      }
    };
    
    // 监听嵌套组件更新事件（来自父组件）
    const handleNestedComponentUpdate = (event) => {
      if (event.type === 'nested-component-update' && event.data.path) {
        console.log('收到嵌套组件更新事件:', event.data.path, event.data.props);
        
        // 简化实现：检查路径是否匹配当前组件
        // 实际项目中可能需要更复杂的路径解析
        const path = event.data.path || [];
        if (path.length > 0 && path[0] === props.props.id) {
          // 找到对应的子组件并更新属性
          const remainingPath = path.slice(1);
          if (remainingPath.length === 0) {
            // 路径指向当前组件的直接子组件
            const childIndex = localChildren.findIndex(child => child.props?.id === event.data.path[1]);
            if (childIndex !== -1) {
              localChildren[childIndex].props = { ...event.data.props };
            }
          }
        }
      }
    };
    
    // 添加对nested-component-update事件的监听
    if (props.isEditable) {
      watch(() => props, (newProps) => {
        if (newProps['onUpdate:nestedComponent'] && typeof newProps['onUpdate:nestedComponent'] === 'function') {
          newProps['onUpdate:nestedComponent'](handleNestedComponentUpdate);
        }
      }, { immediate: true });
    }

    // 子组件事件处理
    const getChildEventListeners = (child, index) => {
      const listeners = {};
      
      // 子元素点击事件（用于选中）
      listeners.click = (e) => {
        e.stopPropagation();
        console.log('选中子组件:', index, child);
        // 直接在当前组件处理选中逻辑
        // 可以添加高亮显示等操作
      };
      
      // 子组件的其他事件 - 在当前组件处理
      if (child.config?.events?.length) {
        child.config.events.forEach(event => {
          listeners[event.name] = (data) => {
            console.log(`子组件事件[${event.name}]:`, index, data);
            // 直接在当前组件处理事件
          };
        });
      }
      
      return listeners;
    };

    // 获取子元素的唯一标识
    const getChildKey = (child, index) => {
      return child.id ? child.id : `child-${index}-${child.config?.componentKey || 'unknown'}`;
    };

    // 移动子组件上移
    const moveChildUp = (index) => {
      console.log('移动子组件上移:', index);
      if (index > 0) {
        // 直接在当前组件操作本地数组
        const temp = localChildren[index];
        localChildren.splice(index, 1);
        localChildren.splice(index - 1, 0, temp);
        
        // 如果需要通知父组件，可以保留emit但添加新的type
        emit('child-event', {
          type: 'local-move-child',
          data: {
            fromIndex: index,
            toIndex: index - 1,
            path: [props.props.id],
            newChildren: [...localChildren]  // 传递更新后的子组件数组
          }
        });
      }
    };

    // 移动子组件下移
    const moveChildDown = (index) => {
      console.log('移动子组件下移:', index);
      if (index < localChildren.length - 1) {
        // 直接在当前组件操作本地数组
        const temp = localChildren[index];
        localChildren.splice(index, 1);
        localChildren.splice(index + 1, 0, temp);
        
        // 如果需要通知父组件，可以保留emit但添加新的type
        emit('child-event', {
          type: 'local-move-child',
          data: {
            fromIndex: index,
            toIndex: index + 1,
            path: [props.props.id],
            newChildren: [...localChildren]  // 传递更新后的子组件数组
          }
        });
      }
    };

    // 请求子组件设置
    const requestChildSettings = (index) => {
      console.log('请求子组件设置:', index, localChildren[index]);
      
      // 发送事件到父组件处理设置请求
      emit('child-event', {
        type: 'request-child-settings',
        data: {
          index,
          path: [props.props.id],
          childComponent: localChildren[index]
        }
      });
    };

    // 删除子组件
    const deleteChild = (index) => {
      console.log('删除子组件:', index);
      // 直接在当前组件删除子组件
      localChildren.splice(index, 1);
      
      // 如果需要通知父组件，可以保留emit但添加新的type
      emit('child-event', {
        type: 'local-delete-child',
        data: {
          index,
          path: [props.props.id],
          newChildren: [...localChildren]  // 传递更新后的子组件数组
        }
      });
    };

    // 请求添加子组件
    const requestAddChild = () => {
      console.log('请求添加子组件到行组件');
      emit('child-event', {
        type: 'request-add-child',
        data: {
          path: [props.props.id],
          componentType: 'row'
        }
      });
    };
    
    // 已经移除了拖拽相关功能，不需要保留这些引用

    return {
      localChildren,  // 返回本地子组件数组供模板使用
      getChildKey,
      getChildEventListeners,
      handleNestedChildEvent,
      moveChildUp,
      moveChildDown,
      requestChildSettings,
      requestAddChild,
      deleteChild
    };
  }
};
</script>

<style scoped>
.column-component {
  border-radius: 0.5rem;
  transition: all 0.2s ease;
}

.column-component:hover {
  border-color: #94bfff;
}

.column-component.drop-target {
  background-color: rgba(22, 93, 255, 0.05);
  border-color: #165DFF;
}

.column-component.is-selected {
  background-color: rgba(22, 93, 255, 0.05);
  border-color: #165DFF;
}

.column-header {
  padding-bottom: 0.5rem;
  border-bottom: 1px dashed #e2e8f0;
}

.header-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.column-component:hover .header-actions {
  opacity: 1;
}

.column-content {
  width: 100%;
}

.children-container {
  width: 100%;
}

.child-wrapper {
  position: relative;
  transition: all 0.2s ease;
}

.child-actions {
  transition: opacity 0.2s ease;
  opacity: 1;
  padding: 4px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.child-actions button {
  z-index: 50;
  min-width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  background-color: white;
}

.child-actions button:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0,0,0,0.15);
}

.child-actions button:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

/* 确保操作按钮始终在最上层 */
.child-wrapper {
  z-index: 1;
}

.child-component {
  transition: all 0.2s ease;
}

.drop-placeholder {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    border-color: #165DFF;
  }
  50% {
    border-color: #7cb3ff;
  }
  100% {
    border-color: #165DFF;
  }
}

.empty-state {
  border: 1px dashed #cbd5e1;
  border-radius: 0.5rem;
  transition: all 0.2s ease;
}

.empty-state:hover {
  border-color: #94bfff;
  background-color: #f8fafc;
}

/* 有子元素时的样式优化 */
.has-children {
  background-color: #fafafa;
}

/* 容器组件特有样式 */
.is-container {
  position: relative;
}

.is-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  border-radius: 0.5rem;
}
</style>